package com.skp.shaphan.actions;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import com.skp.job.ProjectJobException;
import com.skp.shaphan.ShaphanApp;
import com.skp.shaphan.model.ConnectionDetails;
import com.skp.shaphan.ui.ConnectRunnable;
import com.skp.shaphan.ui.connectioncontrols.SQLServerConnectionOptions;

/**
 * Creates a connection to a database
 * @author Stephen Phillips
 *
 */
public class SQLServerConnectAction implements ConnectRunnable {
	private SQLServerConnectionOptions optionsGUI;
	private Connection connection;
	
	/**
	 * Creates the new action attached to a specific dialog
	 * @param serverConnectionOptions the dialog containing the connection information
	 */
	public SQLServerConnectAction(SQLServerConnectionOptions serverConnectionOptions) {
		this.optionsGUI = serverConnectionOptions;
	}
	
	/**
	 * Creates the connection and attaches it to the SQL Editor
	 */
	@Override
	public void run() {
		connect();
		ShaphanApp.getMainWindow().getSQLEditorsPane().setConnection(new ConnectionDetails(connection, ConnectionDetails.CONN_TYPE_SQL_SERVER));
	}

	@Override
	public Connection connect() {
		try {
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
		} catch (ClassNotFoundException e) {
			(new ProjectJobException(e)).displayException();
		}
		String serverName = optionsGUI.getServerName();
		String portNumber = optionsGUI.getPort();
		String userName = optionsGUI.getUser();
		String password = optionsGUI.getPassword();
		try {
			connection = DriverManager.getConnection("jdbc:sqlserver://" + serverName + ":" + portNumber, userName, password);
		} catch (SQLException e) {
			(new ProjectJobException(e)).displayException();
			return null;
		}
		return connection;
	}

}
